package cn.azzhu.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MyBatisUtil {
  //将SqlSession放入到ThreadLocal中，实现与当前线程绑定
  private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

  private static SqlSessionFactory factory = null;

  static {
    try {
     Reader reader = Resources.getResourceAsReader("config.xml");
     factory = new SqlSessionFactoryBuilder().build(reader);
    } catch (IOException e) {
     e.printStackTrace();
     throw new RuntimeException(e);
    }
  }

  private MyBatisUtil(){}

  //获取跟当前线程绑定的SqlSession对象
  public static SqlSession getSqlSession() {
    SqlSession sqlSession = threadLocal.get();
    //如果ThreadLocal中没有，通过SQLSessionFactory创建一个
    if(sqlSession == null) {
     sqlSession = factory.openSession();
     //放入到ThreadLocal中
     threadLocal.set(sqlSession);
    }
    return sqlSession;
  }

  //关闭SqlSession对象
  public static void closeSqlSession() {
    //先从ThreadLocal中取
    SqlSession sqlSession = threadLocal.get();
    //若SqlSession不为null，关闭，并从ThreadLocal中移除
    if(sqlSession != null) {
     sqlSession.close();
     threadLocal.remove();
    }
  }
}
